package com.ywl.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ywl.common.CustomException;
import com.ywl.common.R;
import com.ywl.entity.Comment;
import com.ywl.service.CommentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author ywl
 * @since 2022-08-26
 */
@RestController
@Api(tags = "评论相关接口")
public class CommentController {
    @Autowired
    private CommentService commentService;
    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("评论列表接口")
    @GetMapping("/comment")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "商品id", required = true),
            @ApiImplicitParam(name = "page", value = "当前页号，从0开始", required = true)
    })
    /*@Cacheable(value = "commentCache",
            key = "'comment_' + #id + '_'+#page",
            unless = "#result.getStatus() != 500"
    )*/
    public R<List<Comment>> getCommentList(Long id, Integer page) {
        Page<Comment> commentPage = new Page<>(page + 1, 5);
        commentService.getPage(id, commentPage);

        if (commentPage == null) {
            throw new CustomException("请求失败");
        }
        long current = commentPage.getCurrent();
        long pages = commentPage.getPages();

        if (current == pages) {
            return R.success(commentPage.getRecords(), false);
        } else {
            return R.success(commentPage.getRecords(), true);
        }
    }

    @ApiOperation("提交评论接口")
    @PostMapping("/feelback")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "orderId",value = "订单id",required = true),
        @ApiImplicitParam(name = "feelback",value = "评论内容",required = true)
    })
    //如果用户提交了评论，那么就删除redis中的缓存，key的值为commentCache,
    //因为数据发生了更新，需要从重新去数据库中查询
    /*@CacheEvict(value = "commentCache",allEntries = true)*/
    public R<String> feelBack(Long orderId,String feelback) {
        boolean flag = commentService.saveComment(orderId,feelback);
        return flag?R.success("评论成功"):R.error("评论失败");
    }
}

